package com.hopes.bizz.risk.transfer.handler;

import com.hopes.bizz.common.core.util.StringUtils;
import com.hopes.bizz.risk.common.constant.enums.RiskModDictEnum;
import com.hopes.bizz.risk.control.entity.RiskUnitEntity;
import com.hopes.bizz.risk.control.entity.RiskUnitStopEntity;
import com.hopes.bizz.risk.control.service.RiskUnitService;
import com.hopes.bizz.risk.control.service.RiskUnitStopService;
import com.hopes.bizz.risk.transfer.bean.bo.RiskDataBo;
import com.hopes.bizz.risk.transfer.bean.dto.RiskUnitStopDto;
import com.hopes.bizz.risk.transfer.constant.RiskErrorType;
import com.hopes.bizz.risk.transfer.constant.RiskRequestType;
import com.hopes.bizz.risk.transfer.converter.RiskUnitStopConverter;
import com.hopes.boss.admin.api.resolver.DictResolver;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Objects;

/**
 * @author lyb
 * @version 1.0
 * @description: 风险单元检维修
 * @date 2024/2/4 16:52
 */
@Service
@Slf4j
public class RiskUnitStopHandler extends AbstractRiskData<RiskUnitStopDto> {

    @Resource
    private RiskUnitService riskUnitService;

    @Resource
    private RiskUnitStopService riskUnitStopService;

    @Override
    protected void saveRiskData(RiskUnitStopDto riskUnitStopDto, RiskDataBo riskDataBo) {
        // 校验危险源是否存在
        String riskObjectId = DictResolver.getItemValueByLabel(RiskModDictEnum.risk_object_code, riskUnitStopDto.getHazardCode());
        if (StringUtils.isBlank(riskObjectId)) {
            saveErrorLog(riskUnitStopDto, riskDataBo, RiskErrorType.HAZ_SOURCE_NOT_FOUND);
            return;
        }
        // 风险单元是否存在
        String riskUnitId = riskUnitStopDto.getRiskUnitId();
        RiskUnitEntity riskUnit = riskUnitService.getByUid(riskUnitId);
        if (Objects.isNull(riskUnit)) {
            saveErrorLog(riskUnitStopDto, riskDataBo, RiskErrorType.RISK_UNIT_NOT_FOUND);
            return;
        }
        // 更新、保存
        RiskUnitStopEntity riskUnitStopEntity = RiskUnitStopConverter.INSTANCE.toEntity(riskUnitStopDto);
        riskUnitStopEntity.setRiskUnitId(riskUnit.getId());
        RiskUnitStopEntity riskUnitStop = riskUnitStopService.getByUid(riskUnitStopDto.getId());
        riskUnitStopEntity.setOrgId(riskDataBo.getOrgId());
        if (Objects.isNull(riskUnitStop)) {
            riskUnitStopService.save(riskUnitStopEntity);
        } else {
            riskUnitStopEntity.setId(riskUnitStop.getId());
            riskUnitStopService.updateById(riskUnitStopEntity);
        }
    }

    @Override
    public RiskRequestType getRequestType() {
        return RiskRequestType.RISK_UNIT_STOP;
    }
}
